<template>
	<div class="sales-out-stock-info">
		<div class="main_content">
			<div class="main_content_title">
				<div class="left">
					<span>{{ propUpType === 'add' ? $t('publicBtn.add') : propUpType === 'edit' ? $t('publicBtn.edit') :
						$t('publicBtn.detail') }}</span>
					<template v-for="(item, index) in $route.meta.title">
						<span v-if="languageId === item.langId">{{ item.name }}</span>
					</template>
				</div>
				<div class="right" />
			</div>
			<div class="main_content_con">
				<el-form ref="info" :model="info" :rules="rules" label-width="100px" class="demo-ruleForm">
					<div class="content_info">
						<template v-if="propUpType !== 'detail'">
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.latentName')" prop="saleName">
										<el-input v-model="info.saleName" :placeholder="$t('placeholderTip.enter')" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('publicFormLabel.phone')" prop="salePhone">
										<el-input v-model="info.salePhone" :placeholder="$t('placeholderTip.enter')" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.saleOrderLabel')" prop="saleOrder">
										<el-input v-model="info.saleOrder" :placeholder="$t('placeholderTip.enter')" />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.totalNumLabel')">
										<el-input readonly :value="info.totalNum" :placeholder="$t('placeholderTip.bringOut')" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.totalAmtLabel')">
										<el-input readonly :value="info.totalAmt" :placeholder="$t('placeholderTip.bringOut')" />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('publicFormLabel.remark')">
										<el-input v-model="info.remark" type="textarea" :placeholder="$t('placeholderTip.enter')" />
									</el-form-item>
								</el-col>
							</el-row>
							<div class="line"></div>
							<div class="contentInfo">
								<div class="header">
									<div class="title">{{ $t('text.outStockDetails') }}</div>
									<div class="btn">
										<el-button type="primary" size="mini" @click="addData">{{
											$t('publicBtn.add') }}</el-button>
									</div>
								</div>
								<el-table :data="info.inventoryList" border style="width: 100%">
									<el-table-column prop="code" :label="$t('formLabel.partNumber')" align="center" />
									<el-table-column prop="name" :label="$t('formLabel.partName')" align="center" />
									<el-table-column prop="alias" :label="$t('formLabel.partAnotherName')" align="center" />
									<el-table-column prop="brand" :label="$t('publicFormLabel.brandName')" align="center" width="200px" />
									<el-table-column prop="stockNum" :label="$t('formLabel.stockNumLabel')" align="center" />
									<el-table-column :label="$t('formLabel.priceLabel')" prop="price" align="center" />
									<el-table-column :label="$t('formLabel.warehouseName')" align="center" width="200px">
										<template slot-scope="scope">
											<el-form-item label=" " label-width="2px" :prop="'inventoryList.' + scope.$index + '.warehouseId'"
												:rules="rules.warehouseId">
												<el-select style="width:93%" v-model="scope.row.warehouseId" filterable
													:placeholder="$t('placeholderTip.pSelect')" @change="getPositionList(scope.row, $event)">
													<el-option v-for="item in scope.row.stockWarehouses" :key="item.id" :label="item.name"
														:value="item.id" />
												</el-select>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column :label="$t('formLabel.storageLocation')" align="center" width="200px">
										<template slot-scope="scope">
											<el-form-item label=" " label-width="2px" :prop="'inventoryList.' + scope.$index + '.positionId'"
												:rules="rules.positionId">
												<el-select style="width:93%" v-model="scope.row.positionId" filterable
													:placeholder="$t('placeholderTip.pSelect')"
													@change="getpositionNum(scope.row, scope.row.positionList, $event)">
													<el-option v-for="item in scope.row.positionList" :key="item.id" :label="item.name"
														:value="item.id" />
												</el-select>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column prop="positionNum" :label="$t('formLabel.positionNumLabel')" align="center" />
									<el-table-column :label="$t('formLabel.totalNums')" align="center" width="200px">
										<template slot-scope="scope">
											<el-form-item label=" " label-width="2px" :prop="'inventoryList.' + scope.$index + '.num'"
												:rules="rules.num">
												<el-input v-model="scope.row.num" :placeholder="$t('placeholderTip.enter')"
													style="width:93%"></el-input>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column :label="$t('formLabel.totalAmountLabel')" prop="amount" align="center" />
									<el-table-column fixed="right" :label="$t('publicFormLabel.operate')" align="center" width="80px">
										<template slot-scope="scope">
											<el-button @click="deleteRow(scope.$index)" type="text" size="small">{{
												$t('publicBtn.delete') }}</el-button>
										</template>
									</el-table-column>
								</el-table>
							</div>
						</template>
						<template v-else>
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.outOrder')">
										<el-input readonly :value="info.outOrder" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.latentName')" prop="saleName">
										<el-input readonly v-model="info.saleName" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('publicFormLabel.phone')" prop="salePhone">
										<el-input readonly v-model="info.salePhone" />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.saleOrderLabel')" prop="saleOrder">
										<el-input readonly v-model="info.saleOrder" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.totalNumLabel')">
										<el-input readonly :value="info.totalNum" />
									</el-form-item>
								</el-col>
								<el-col :span="8">
									<el-form-item :label="$t('formLabel.totalAmtLabel')">
										<el-input readonly :value="info.totalAmt" />
									</el-form-item>
								</el-col>
							</el-row>
							<el-row :gutter="24">
								<el-col :span="8">
									<el-form-item :label="$t('publicFormLabel.remark')">
										<el-input readonly v-model="info.remark" type="textarea" />
									</el-form-item>
								</el-col>
							</el-row>
							<div class="line"></div>
							<div class="contentInfo">
								<div class="header">
									<div class="title">{{ $t('text.outStockDetails') }}</div>
								</div>
								<el-table :data="info.inventoryList" border style="width: 100%">
									<el-table-column prop="code" :label="$t('formLabel.partNumber')" align="center" />
									<el-table-column prop="name" :label="$t('formLabel.partName')" align="center" />
									<el-table-column prop="alias" :label="$t('formLabel.partAnotherName')" align="center" />
									<el-table-column prop="brand" :label="$t('publicFormLabel.brandName')" align="center" width="200px" />
									<el-table-column :label="$t('formLabel.priceLabel')" prop="price" align="center" />
									<el-table-column :label="$t('formLabel.warehouseName')" align="center" prop="warehouseName" />
									<el-table-column :label="$t('formLabel.storageLocation')" align="center">
										<template slot-scope="scope">
											{{ scope.row.positionName }}
										</template>
									</el-table-column>
									<el-table-column :label="$t('formLabel.totalNums')" align="center">
										<template slot-scope="scope">
											{{ scope.row.num }}
										</template>
									</el-table-column>
									<el-table-column :label="$t('formLabel.totalAmountLabel')" prop="amount" align="center" />
								</el-table>
							</div>
						</template>
					</div>
				</el-form>
				<div class="footerBtn">
					<el-button @click="getCancle">{{ propUpType !== 'detail' ? $t('el.popconfirm.cancelButtonText') :
						$t('el.popconfirm.close') }}</el-button>
					<el-button v-if="propUpType !== 'detail'" type="primary" @click="addSubmitForm"
						v-loading.fullscreen.lock="fullscreenLoading">{{ $t('el.popconfirm.confirmButtonText') }}</el-button>
				</div>
			</div>
		</div>
		<!-- 添加配件 -->
		<InventoryMode ref="InventoryMode"></InventoryMode>
	</div>
</template>
<script>
import {
	getMaterialOutboundInfo,
	getMaterialOutboundSaveSale,
	getMaterialIntoStockWarehouses
} from '@/api/parts-manager'
import defaultSettings from '@/settings'
import InventoryMode from '@/components/Inventory-mode'

export default {
	name: '',
	components: {
		InventoryMode,
	},
	data() {
		return {
			BASE_IMG: defaultSettings.BASE_IMG,
			info: {
				saleName: '',//姓名
				salePhone: '',//电话
				saleOrder: '',//出库单号
				totalAmt: '',//出库总金额
				totalNum: '',//出库总数
				remark: '',//备注
				inventoryList: [],
			},
			warehouseList: [],//仓库
			flag: true,
			rules: {
				num: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					}
				],
				warehouseId: [
					{
						required: true,
						message: this.$t('placeholderTip.pSelect'),
						trigger: 'change'
					}
				],
				positionId: [
					{
						required: true,
						message: this.$t('placeholderTip.pSelect'),
						trigger: 'change'
					}
				],
				saleOrder: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					}
				],
				salePhone: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					}
				],
				saleName: [
					{
						required: true,
						message: this.$t('placeholderTip.enter'),
						trigger: 'blur'
					}
				],
			},
			propUpType: '', // 'add' edit detail
			fullscreenLoading: false,
		}
	},
	computed: {
		languageId() {
			// 固定语种ID  1:中文  2:英文 3:俄文 4:乌语
			return this.$store.getters.languageId
		},
	},
	watch: {
		'info.inventoryList': {
			handler: function (val) {
				if (val.length > 0) {
					if (this.propUpType === 'add') {
						var sumNumber = 0
						var number = []
						var amountNumber = 0
						var totalAmts = []
						this.info.inventoryList.map(i => {
							// 出库总数
							if (i.num) {
								number.push(Number(i.num))
							}
							// 总价 库存*单价
							if (i.num && i.price) {
								// 总价 库存 * 单价
								i.amount = Number(i.num) * Number(i.price)
								totalAmts.push(i.amount)
							}
						})
						number.forEach(item => {
							sumNumber = sumNumber + item
						})

						totalAmts.forEach(item => {
							amountNumber = amountNumber + item
						})
						this.info.totalNum = sumNumber //出库总数
						this.info.totalAmt = amountNumber //出库总金额
					}
				}
			},
			deep: true
		}
	},
	mounted() {
		window._vm = this
		this.propUpType = this.$route.query.propUpType
		if (this.$route.query.propUpType === 'add') {
		} else if (this.$route.query.id) {
			this.getInfo(this.$route.query.id)
		}
	},
	created() {
		console.log('created')
	},
	activated() { },

	destroyed() { },
	methods: {
		// 根据仓库id 选择库位
		getPositionList(tar, id) {
			tar.positionList = []
			tar.positionId = ''
			tar.positionNum = ''
			tar.stockWarehouses.map(i => {
				if (id === i.id) {
					tar.positionList = i.positions || []
				}
			})
		},
		// 获取库位数量
		getpositionNum(tar, list, id) {
			tar.positionNum = ''
			list.map(i => {
				if (id === i.id) {
					tar.positionNum = i.num
				}
			})
		},
		// 添加明细按钮
		addData() {
			this.$refs.InventoryMode.getOpen()
		},
		// 处理配件列表选中的数据
		getCheckoutData(tar) {
			var data = JSON.parse(tar)
			var obj = {
				materialId: data.materialId,
				code: data.code,
				name: data.name,
				alias: data.alias,
				brand: data.brand,
				stockNum: data.stockNum,//库存总数
				price: data.wholesalePrice,//单价
				amount: '',//总价
				positionId: '',//库位id
				positionList: [],//库位
				positionNum: '',//库位数量
				warehouseId: '',//仓库id
				stockWarehouses: [],//仓库、库位数组
				num: '',//出库数量
			}
			//处理仓库 库位接口参数
			getMaterialIntoStockWarehouses(obj.materialId).then(res => {
				if (res.code === 200) {
					obj.stockWarehouses = res.data || []
				}
			})
			// 判断添加数据是否重复
			const checkId = (items, idToCheck) => {
				return items.filter(item => item.materialId === idToCheck).length > 0;
			}
			// 不重复 push数据
			if (!checkId(this.info.inventoryList, data.id)) {
				this.info.inventoryList.push(obj)
			}
		},

		// 删除明细
		deleteRow(index) {
			this.info.inventoryList.splice(index, 1)
			this.$forceUpdate() // 强制跟新
		},
		// 提交
		addSubmitForm() {
			this.$refs['info'].validate(valid => {
				if (valid) {
					var obj = JSON.parse(JSON.stringify(this.info))
					if (obj.inventoryList.length === 0) {
						this.$message({
							showClose: true,
							message: this.$t('text.intoInventoriestipInfo'),
							type: 'warning'
						})
						return false
					}
					for (var i = 0; i < obj.inventoryList.length; i++) {
						var item = obj.inventoryList[i]
						// 出库数量必须小于等于库位书库
						if (Number(item.num) > item.positionNum) {
							this.$message({
								showClose: true,
								message: this.$t('text.stockTip') + `${i + 1},` + this.$t('text.stockTip1'),
								type: 'warning'
							})
							return false
						}
					}
					var params = {
						inventoryList: obj.inventoryList,
						sale: {
							saleName: obj.saleName,//姓名
							salePhone: obj.salePhone,//电话
							saleOrder: obj.saleOrder,//出库单号
						},
						totalAmt: obj.totalAmt,//出库总金额
						totalNum: obj.totalNum,//出库总数
						remark: obj.remark,//备注
					}
					this.fullscreenLoading = true
					if (this.propUpType === 'add') {
						getMaterialOutboundSaveSale(params)
							.then(res => {
								if (res.code === 200) {
									this.$message({
										showClose: true,
										message: this.$t('text.addSucceedTip'),
										type: 'success'
									})
									this.fullscreenLoading = false
									this.getCancle()
								}
							})
							.catch(err => {
								this.fullscreenLoading = false
								console.log(err, 'err')
							})
					}
				} else {
					return false
				}
			})
		},
		// 详情
		getInfo(id) {
			const loading = this.$loading({
				lock: true,
				text: this.$t('text.loading'),
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})
			getMaterialOutboundInfo(id).then(res => {
				if (res.code === 200) {
					this.info = {
						saleName: res.data.sale.saleName,//姓名
						salePhone: res.data.sale.salePhone,//电话
						saleOrder: res.data.sale.saleOrder,//单号
						totalAmt: res.data.totalAmt,//出库总金额
						totalNum: res.data.totalNum,//出库总数
						remark: res.data.remark,//备注
						outOrder: res.data.outOrder,
						inventoryList: res.data.inventoryList,
					}
					loading.close()
				}
			}).catch(() => {
				loading.close()
			})
		},
		// 取消
		getCancle() {
			this.$store.state.tagsView.visitedViews.splice(
				this.$store.state.tagsView.visitedViews.findIndex(
					item => item.path === this.$route.path
				),
				1
			)
			this.$router.go(-1)
		},


	}
}
</script>
<style lang="scss" scoped>
.sales-out-stock-info {
	height: 100%;
	width: 100%;
	padding: 20px;
	box-sizing: border-box;
	overflow: hidden;

	&>.main_content {
		width: 99.9%;
		height: 100%;

		&>.main_content_title {
			margin-bottom: 10px;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
		}

		.main_content_con {
			height: calc(100% - 40px);
			width: 100%;
			display: inline-block;
			border: 1px solid #dfe6ec;
			padding: 20px;


			&>.el-form {
				width: 100%;
				height: calc(100% - 40px);

				&>.content_info {
					width: 100%;
					height: 100%;
					overflow: hidden;
					overflow-y: auto;

					.line {
						height: 1px;
						border: 1px solid #ebeef5;
					}

					.el-table {
						::v-deep th {
							line-height: 40px;
							padding: unset;
							background-color: #f2f2f2;
						}
					}
				}


			}

			.footerBtn {
				width: 100%;
				display: flex;
				justify-content: center;
			}

			.cardBox {
				width: 104px;
				height: auto;
				float: left;
				position: relative;

				&>.name {
					text-align: center;
					color: #999;
					font-size: 12px;
				}
			}

			.el-button:hover,
			.el-button:focus {
				color: #000;
			}

			.contentInfo {
				margin-top: 22px;

				&>.header {
					margin-bottom: 22px;
					display: flex;
					justify-content: space-between;
					color: #606266;

					&>.title {
						font-size: 14px;
						font-weight: bold;
					}

				}
			}





		}
	}
}
</style>
<style lang="scss" scoped>
.main_content_con_md {
	width: 100%;
	height: calc(100% - 25px);
	overflow: auto;
	display: inline-block;

	.el-table {
		::v-deep .el-icon-arrow-right {
			font-weight: 600;
		}

		::v-deep .el-form-item__error {
			left: 5%;
		}

		::v-deep .el-table__header .el-checkbox {
			display: none !important;
		}

		::v-deep th {
			padding: unset;
			background-color: #f2f2f2;

			.header_item {
				height: 39px;
				line-height: 39px;
				display: flex;
				justify-content: center;
				align-items: center;

				&>.keySort {
					width: 23px;
					height: 21px;
					position: relative;
					display: inline-block;

					&>.el-icon-caret-top {
						position: absolute;
						top: 0;
						right: 0;
						left: 0;
						margin: auto;
						cursor: pointer;
					}

					&>.el-icon-caret-bottom {
						position: absolute;
						bottom: 0;
						right: 0;
						left: 0;
						margin: auto;
						cursor: pointer;
					}
				}
			}
		}
	}
}
</style>
<style lang="scss" scoped>
::v-deep .add_dialog {
	height: calc(100% - 30vh) !important;
	position: relative;

	.el-dialog__header {
		border-bottom: 1px solid #e4e4e4;
		text-align: left;
	}

	.el-dialog__body {
		height: calc(100% - 125px) !important;

	}

	.el-dialog__footer {
		border-top: 1px solid #e4e4e4;
		text-align: right;
	}

	.el-button:hover,
	.el-button:focus {
		color: #000;
	}
}
</style>
